package fun.stgoder.easydarwin.jobs.comm.util;

import fun.stgoder.easydarwin.jobs.comm.Constants;
import fun.stgoder.easydarwin.jobs.comm.model.Cmd;
import org.apache.commons.lang3.StringUtils;

import java.io.File;

public class MediaUtil {

    public static String getVideoDurationText(String videoPath) {
        try {
            long start = System.currentTimeMillis();
            String str = ProcessUtil.exec(
                    new Cmd()
                            .add(Constants.FFPROBE_PATH)
                            .add("-v")
                            .add("error")
                            .add("-show_entries")
                            .add("format=duration")
                            .add("-of")
                            .add("default=noprint_wrappers=1:nokey=1")
                            .add("-i")
                            .add(videoPath))
                    .getOutput();
            System.out.println(str);
            System.out.println(System.currentTimeMillis() - start);
            str = StringUtils.chomp(str);
            String duration = StringUtils.strip(str);
            return duration;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "0.000000";
    }

    public static float getVideoDuration(String durationText) {
        try {
            return Float.valueOf(durationText);
        } catch (Exception e) {
            System.out.println(e.getMessage());
            return 0.0f;
        }
    }

    public static void convertTsToMp4(String recordFileDir, String jobId) {
        try {
            long start = System.currentTimeMillis();
            String tsFilePath = recordFileDir + File.separator + jobId + Constants.RECORD_FILE_SUFFIX;
            String mp4FilePath = recordFileDir + File.separator + jobId + ".mp4";
            int exitValue = ProcessUtil.execRedirect(new Cmd()
                            .add(Constants.FFMPEG_PATH)
                            .add("-i")
                            .add(tsFilePath)
                            .add("-acodec")
                            .add("copy")
                            .add("-vcodec")
                            .add("copy")
                            .add("-f")
                            .add("mp4")
                            .add(mp4FilePath)
                    , recordFileDir);
            System.out.println(exitValue);
            long end = System.currentTimeMillis();
            System.out.println("convertTsToMp4 cost: " + (end - start));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private MediaUtil() {
    }

    public static void main(String[] args) {
        // MediaUtil.getVideoDurationText("D:\\sof\\EasyDarwin-windows-8.1.0-1901141151-all\\m3u8\\cam64\\record\\20191009\\5d9d6401853f4913d483977f.ts");
        MediaUtil.convertTsToMp4("C:\\Users\\stgoder\\Desktop",
                "5dd1fd16c94c201063099f9f");
    }
}
